package com.hcloud.common.social.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hcloud.common.social.config.GiteeConfig;
import com.hcloud.common.social.config.SocialRestTemplate;
import com.hcloud.common.social.exception.WrongGiteeCodeException;
import com.hcloud.common.social.service.GiteeInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Auther hepangui
 * @Date 2018/12/13
 */
@Service
public class GiteeInfoServiceImpl implements GiteeInfoService {

    private final String TOKEN_URL = "https://gitee.com/oauth/token?grant_type=authorization_code" +
            "&code={code}&client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}";

    private final String INFO_URL = "https://gitee.com/api/v5/user?access_token={access_token}";

    @Autowired
    private GiteeConfig giteeConfig;

    @Override
    public String getOpenId(String code) {
        try {
            String result = SocialRestTemplate.getRestTemplate().postForObject(
                    TOKEN_URL.replace("{client_id}", giteeConfig.getAppId())
                            .replace("{code}", code)
                            .replace("{redirect_uri}", giteeConfig.getRedirectUri())
                            .replace("{client_secret}", giteeConfig.getAppSecret()),
                   null ,String.class
            );
            System.out.println(result);
            Map map = JSONObject.parseObject(result, Map.class);
            String accessToken = (String) (map.get("access_token"));
            if (accessToken != null && !"".equals(accessToken)) {
                result = SocialRestTemplate.getRestTemplate().getForObject(INFO_URL.replace("{access_token}", accessToken),
                        String.class);
                map = JSONObject.parseObject(result, Map.class);

                Object id = map.get("id");
                if(id!=null){
                    return String.valueOf(id);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new WrongGiteeCodeException();

    }
}
